package com.sdry.service.impl.hpf;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.sdry.mapper.hpf.ApprovalRecordMapper;
import com.sdry.mapper.hpf.BomMapper;
import com.sdry.mapper.hpf.CacheAreaInMapper;
import com.sdry.mapper.hpf.CacheAreaMapper;
import com.sdry.mapper.hpf.LineSideLibraryMapper;
import com.sdry.mapper.hpf.MemberMapper;
import com.sdry.mapper.hpf.PartMapper;
import com.sdry.mapper.hpf.PickApplyDetailMapper;
import com.sdry.mapper.hpf.PickApplyMapper;
import com.sdry.mapper.hpf.ProductMapper;
import com.sdry.model.hpf.ApprovalRecord;
import com.sdry.model.hpf.Bom;
import com.sdry.model.hpf.CacheArea;
import com.sdry.model.hpf.CacheAreaIn;
import com.sdry.model.hpf.LineSideLibrary;
import com.sdry.model.hpf.LineSideLibraryOut;
import com.sdry.model.hpf.MaterialComparison;
import com.sdry.model.hpf.Part;
import com.sdry.model.hpf.PickApply;
import com.sdry.model.hpf.PickApplyDetail;
import com.sdry.model.hpf.Product;
import com.sdry.model.jyy.Shedudetail;
import com.sdry.model.llm.User;
import com.sdry.service.hpf.PickApplyService;
import com.sdry.utils.PushExample;
import com.sdry.utils.SerialComm4MainWindows;
import com.sdry.utils.StringUtil;

/**
 * @ClassName: PickApplyServiceImpl 
 * @Description:领料申请单Service实现
 * @Author hpf
 * @Date 2018年10月9日 下午3:07:10 
 * @version 1.0
 */
@Service
public class PickApplyServiceImpl implements PickApplyService {

	@Resource
	private PickApplyMapper pickApplyMapper;
	@Resource
	private PickApplyDetailMapper pickApplyDetailMapper;
	@Resource
	private LineSideLibraryMapper lineSideLibraryMapper;
	@Resource
	private CacheAreaMapper cacheAreaMapper;
	@Resource
	private ProductMapper productMapper;
	@Resource
	private BomMapper bomMapper;
	@Resource
	private PartMapper partMapper;
	@Resource
	private ApprovalRecordMapper approvalRecordMapper;
	@Resource
	private MemberMapper memberMapper;
	@Resource
	private CacheAreaInMapper cacheAreaInMapper;
	
	/**
	 * 条件查询领料申请单总数
	 * @param pickApply 查询条件
	 * @return
	 */
	public Integer countPickApply(PickApply pickApply) {
		// TODO Auto-generated method stub
		return pickApplyMapper.countPickApply(pickApply);
	}

	/**
	 * 分页查询领料申请单
	 * @param map 查询条件
	 * @return
	 */
	public List<PickApply> listPagePickApply(Map<String, Object> map) {
		// TODO Auto-generated method stub
		return pickApplyMapper.listPagePickApply(map);
	}

	/**
	 * 条件查询所有领料申请单
	 * @param pickApply 查询条件
	 * @return
	 */
	public List<PickApply> listAllPickApply(PickApply pickApply) {
		// TODO Auto-generated method stub
		return pickApplyMapper.listAllPickApply(pickApply);
	}

	/**
	 * 新增领料申请单
	 * @param pickApply 领料申请单实体
	 * @param stockNum 存货编码组成的数组
	 * @param stockName 存货名称组成的数组
	 * @param stockModel 规格型号组成的数组
	 * @param paunit 主计量单位组成的数组
	 * @param packNorm 包装规格组成的数组
	 * @param batch 批次号组成的数组
	 * @param quantity 数量组成的数组
	 * @return
	 */
	@Transactional(rollbackFor={Exception.class})
	public Integer insertPickApply(PickApply pickApply,String[] stockNum,String[] stockName,
			String[] stockModel,String[] paunit,String[] packNorm,String[] batch,String[] quantity) {
		// TODO Auto-generated method stub
		int isSuccess = 0;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			if ("2".equals(pickApply.getReserve5())) {
				for (int i = 0; i < stockNum.length; i++) {
					//给AGV小车命令拉料
					SerialComm4MainWindows.sendMsg("COM3", "线边库缺料:", stockNum[i], stockName[i], stockModel[i], paunit[i], packNorm[i], batch[i], quantity[i], "2", sdf.format(pickApply.getDemandDate()));
					isSuccess = -1;
				}
				(new SerialComm4MainWindows()).connect("COM3");
			} else {
				pickApply.setReserve1("0");
				pickApply.setPickNum("P"+getRandomNumber(12));
				pickApply.setReserve4("2");
				int pickID = pickApplyMapper.insertPickApply(pickApply);
				isSuccess = pickID;
				for (int i = 0; i < stockNum.length; i++) {
					PickApplyDetail pickApplyDetail = new PickApplyDetail();
					pickApplyDetail.setPickID(Long.parseLong(pickID+""));
					pickApplyDetail.setStockNum(stockNum[i]);
					pickApplyDetail.setStockName(stockName[i]);
					pickApplyDetail.setStockModel(stockModel[i]);
					pickApplyDetail.setReserve1(paunit[i]);
					pickApplyDetail.setReserve2(packNorm[i]);
					pickApplyDetail.setReserve3(batch[i]);
					pickApplyDetail.setQuantity(quantity[i]);
					isSuccess = pickApplyDetailMapper.insertPickApplyDetail(pickApplyDetail);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();     
	        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	        isSuccess = 0;
		}
		return isSuccess;
	}

	/**
	 * 修改领料申请单
	 * @param pickApply 领料申请单实体
	 * @param stockNum 存货编码组成的数组
	 * @param stockName 存货名称组成的数组
	 * @param stockModel 规格型号组成的数组
	 * @param quantity 数量组成的数组
	 * @return
	 */
	@Transactional(rollbackFor={Exception.class})
	public Integer updatePickApply(PickApply pickApply,String[] stockNum,
			String[] stockName,String[] stockModel,String[] quantity) {
		// TODO Auto-generated method stub
		int isSuccess = 0;
		try {
			pickApply.setReserve1("0");
			isSuccess = pickApplyMapper.updatePickApply(pickApply);
			isSuccess = pickApplyDetailMapper.deletePickApplyDetailByPickID(pickApply.getPickID());
			for (int i = 0; i < stockNum.length; i++) {
				PickApplyDetail pickApplyDetail = new PickApplyDetail();
				pickApplyDetail.setPickID(pickApply.getPickID());
				pickApplyDetail.setStockNum(stockNum[i]);
				pickApplyDetail.setStockName(stockName[i]);
				pickApplyDetail.setStockModel(stockModel[i]);
				pickApplyDetail.setQuantity(quantity[i]);
				isSuccess = pickApplyDetailMapper.insertPickApplyDetail(pickApplyDetail);
			}
		} catch (Exception e) {
			e.printStackTrace();     
	        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	        isSuccess = 0;
		}
		return isSuccess;
	}

	/**
	 * 根据ID删除领料申请单
	 * @param pickIDs 领料申请单ID拼接字符串（以，分割）
	 * @return
	 */
	@Transactional(rollbackFor={Exception.class})
	public Integer deletePickApply(String pickIDs) {
		// TODO Auto-generated method stub
		int isSuccess = 0;
		try {
			String[] ids = pickIDs.split(",");
			for (int i = 0; i < ids.length; i++) {
				isSuccess = pickApplyMapper.deletePickApply(Long.parseLong(ids[i]));
				isSuccess = pickApplyDetailMapper.deletePickApplyDetailByPickID(Long.parseLong(ids[i]));
			}
		} catch (Exception e) {
			e.printStackTrace();     
	        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	        isSuccess = 0;
		}
		return isSuccess;
	}
	
	/**
	 * 根据ID审批领料申请单
	 * @param pickIDs 领料申请单ID拼接字符串（以，分割）
	 * @return
	 */
	@Transactional(rollbackFor={Exception.class})
	public Integer approvalPickApply(String pickIDs,Long ztree,HttpSession session) {
		// TODO Auto-generated method stub
		int isSuccess = 0;
		try {
			User user = (User) session.getAttribute("currentUser");
			String[] ids = pickIDs.split(",");
			for (int i = 0; i < ids.length; i++) {
				PickApply pickApply = pickApplyMapper.findPickApplyByID(Long.parseLong(ids[i]));
				//pickApply.setApprovalDate(new Date());
				//pickApply.setApplicant(ztree);
				pickApply.setReserve1("1");
				isSuccess = pickApplyMapper.updatePickApply(pickApply);
				ApprovalRecord approvalRecord = new ApprovalRecord();
				approvalRecord.setPickID(Long.parseLong(ids[i]));
				approvalRecord.setApprovalType("提交领料申请单审批");
				approvalRecord.setSubmitDate(new Date());
				approvalRecord.setSubmitterID(user.getUid());
				approvalRecord.setApproverID(ztree);
				approvalRecord.setStatus(1);
				approvalRecord.setReserve5("0");
				isSuccess = approvalRecordMapper.insertApprovalRecord(approvalRecord);
				User u = memberMapper.findUserByID(ztree);
				isSuccess = PushExample.testSendPush("审批消息", "领料申请单审批", u.getUserName(), "1");
			}
		} catch (Exception e) {
			e.printStackTrace();     
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			isSuccess = 0;
		}
		return isSuccess;
	}

	/**
	 * 生成领料单
	 * @param remark1 排产单日期
	 * @return
	 */
	public PickApply generatePickApply(String remark1) {
		// TODO Auto-generated method stub
		Shedudetail shedudetail = pickApplyMapper.findShedudetailByDate(remark1);
		SimpleDateFormat format = new SimpleDateFormat();
        format.applyPattern("yyyy-MM-dd");
		if (null != shedudetail) {
			PickApply pickApply = new PickApply();
			pickApply.setGenerateOrderID(shedudetail.getId());
			try {
				pickApply.setDemandDate(format.parse(remark1));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			pickApply.setPickDate(new Date());
			//pickApply.setPickDept(Long.parseLong("1"));//制单人部门ID
			//pickApply.setPickPerson(Long.parseLong("1"));//制单人ID
			String b1 = shedudetail.getB1();//0960T 个数
			String c1 = shedudetail.getC1();//0980T	个数
			String d1 = shedudetail.getD1();//1080C	个数
			String e1 = shedudetail.getE1();//1060B 个数
			List<Product> pList = productMapper.listAllProduct(new Product());
			List<Bom> b_boms = new ArrayList<>();
			List<Bom> c_boms = new ArrayList<>();
			List<Bom> d_boms = new ArrayList<>();
			List<Bom> e_boms = new ArrayList<>();
			for (int i = 0; i < pList.size(); i++) {
				Product p = pList.get(i);
				if (p.getPnum().equals("PSH2-0960-T-01")) {
					b_boms = bomMapper.listAllBom(p.getPid());
				} else if (p.getPnum().equals("PSH2-0980-T-02")) {
					c_boms = bomMapper.listAllBom(p.getPid());
				} else if (p.getPnum().equals("PSH1-1080-C-04")) {
					d_boms = bomMapper.listAllBom(p.getPid());
				} else {
					e_boms = bomMapper.listAllBom(p.getPid());
				}
			}
			
			List<Bom> all_boms = new ArrayList<>();
			if (!"".equals(b1)) {
				for (int i = 0; i < b_boms.size(); i++) {
					Bom bom = new Bom();
					bom.setPaid(b_boms.get(i).getPaid());
					bom.setNumber(StringUtil.calcFloatValue(b_boms.get(i).getNumber(), b1, "multiply"));
					//bom.setNumber(b_boms.get(i).getNumber()*Integer.parseInt(b1));
					all_boms.add(bom);
				}
			}
			if (!"".equals(c1)) {
				for (int i = 0; i < c_boms.size(); i++) {
					Bom bom = new Bom();
					bom.setPaid(c_boms.get(i).getPaid());
					bom.setNumber(StringUtil.calcFloatValue(c_boms.get(i).getNumber(), c1, "multiply"));
					//bom.setNumber(c_boms.get(i).getNumber()*Integer.parseInt(c1));
					all_boms.add(bom);
				}
			}
			if (!"".equals(d1)) {
				for (int i = 0; i < d_boms.size(); i++) {
					Bom bom = new Bom();
					bom.setPaid(d_boms.get(i).getPaid());
					bom.setNumber(StringUtil.calcFloatValue(d_boms.get(i).getNumber(), d1, "multiply"));
					//bom.setNumber(d_boms.get(i).getNumber()*Integer.parseInt(d1));
					all_boms.add(bom);
				}
			}
			if (!"".equals(e1)) {
				for (int i = 0; i < e_boms.size(); i++) {
					Bom bom = new Bom();
					bom.setPaid(e_boms.get(i).getPaid());
					bom.setNumber(StringUtil.calcFloatValue(e_boms.get(i).getNumber(), e1, "multiply"));
					//bom.setNumber(e_boms.get(i).getNumber()*Integer.parseInt(e1));
					all_boms.add(bom);
				}
			}
			List<Bom> all_boms2 = new ArrayList<>();
			for (int i = 0; i < all_boms.size(); i++) {
				Bom bom = all_boms.get(i);
				String number = "0";
				for (int j = 0; j < all_boms.size(); j++) {
					if (bom.getPaid().equals(all_boms.get(j).getPaid())) {
						number = StringUtil.calcFloatValue(number, all_boms.get(j).getNumber(), "add");
						//number = number + all_boms.get(j).getNumber();
					}
				}
				Bom b = new Bom();
				b.setPaid(bom.getPaid());
				b.setNumber(number);
				all_boms2.add(b);
			}
			for (int i = 0; i < all_boms2.size() -1; i++) {
				for (int j = all_boms2.size() - 1; j > i; j--) {
					if (all_boms2.get(i).getPaid().equals(all_boms2.get(j).getPaid())) {
						all_boms2.remove(j);
					}
				}
			}
			List<PickApplyDetail> pickApplyDetailList = new ArrayList<>();
			int num = 0;
			String turnNumber = "0";
			for (int i = 0; i < all_boms2.size(); i++) {
				Bom bom = all_boms2.get(i);
				Part part = partMapper.findPartByPaid(bom.getPaid());
				String lQuantity = "0";
				String cQuantity = "0";
				LineSideLibrary lineSideLibrary = lineSideLibraryMapper.findLineSideLibraryByPaID(bom.getPaid());
				if (lineSideLibrary != null) {
					if (lineSideLibrary.getReserve1() != null && !"".equals(lineSideLibrary.getReserve1())) {
						lQuantity = lineSideLibrary.getReserve1();
					} else {
						lQuantity = lineSideLibrary.getQuantity();
					}
				}
				//Bom值减去线边库的库存大于0
				if (Float.parseFloat(StringUtil.calcFloatValue(bom.getNumber(), lQuantity, "subtract")) > 0) {
					CacheArea cacheArea = cacheAreaMapper.findCacheAreaByPaID(bom.getPaid());
					if (cacheArea != null) {
						if (cacheArea.getReserve1() != null && !"".equals(cacheArea.getReserve1())) {
							cQuantity = cacheArea.getReserve1();
						} else {
							cQuantity = cacheArea.getQuantity();
						}
						LineSideLibrary lSideLibrary = new LineSideLibrary();
						lSideLibrary.setPaID(cacheArea.getPaID());
						lSideLibrary.setBatch(cacheArea.getBatch());
						LineSideLibrary library = lineSideLibraryMapper.findLineSideLibrary(lSideLibrary);
						if (library != null) {
							if (library.getReserve1() != null && !"".equals(library.getReserve1())) {
								lQuantity = library.getReserve1();
							} else {
								lQuantity = library.getQuantity();
							}
						} else {
							lQuantity = "0";
						}
					}
					
					String other1 = StringUtil.calcFloatValue(bom.getNumber(), lQuantity, "subtract");
					//bom值减去线边库再减去缓存区
					if (Float.parseFloat(StringUtil.calcFloatValue(other1, cQuantity, "subtract")) > 0) {
						num = 1;
						pickApply.setReserve5("3");
						PickApplyDetail pickApplyDetail = new PickApplyDetail();
						pickApplyDetail.setStockNum(part.getPanum());
						pickApplyDetail.setStockName(part.getPaname());
						pickApplyDetail.setStockModel(part.getPamodel());
						pickApplyDetail.setReserve1(part.getParemark1());
						pickApplyDetail.setReserve2(part.getParemark2());
						if (cacheArea != null) {
							pickApplyDetail.setReserve3(cacheArea.getBatch());
						} else {
							pickApplyDetail.setReserve3("");
						}
						pickApplyDetail.setReserve5(bom.getNumber());
						pickApplyDetail.setQuantity(StringUtil.calcFloatValue(StringUtil.calcFloatValue(bom.getNumber(), lQuantity, "subtract"), cQuantity, "subtract"));
						pickApplyDetailList.add(pickApplyDetail);
					} else {
						if (num == 0) {
							pickApply.setReserve5("2");
							turnNumber = "2";
							PickApplyDetail pickApplyDetail = new PickApplyDetail();
							pickApplyDetail.setStockNum(part.getPanum());
							pickApplyDetail.setStockName(part.getPaname());
							pickApplyDetail.setStockModel(part.getPamodel());
							pickApplyDetail.setReserve1(part.getParemark1());
							pickApplyDetail.setReserve2(part.getParemark2());
							pickApplyDetail.setReserve3(cacheArea.getBatch());
							pickApplyDetail.setReserve4(cQuantity+"");
							pickApplyDetail.setReserve5(bom.getNumber()+"");
							pickApplyDetail.setQuantity(StringUtil.calcFloatValue(bom.getNumber(), lQuantity, "subtract"));
							pickApplyDetailList.add(pickApplyDetail);
						}
					}
				} else {
					pickApply.setReserve5("1");
				}
			}
			//如果有叫料申请，则返回必须是叫料
			if(!"0".equals(turnNumber)){
				pickApply.setReserve5(turnNumber);
			}
			pickApply.setPickApplyDetailList(pickApplyDetailList);
			PickApply pApply = pickApplyMapper.findLastPickApply();
			if (pApply == null) {
				pickApply.setReserve2("");
				pickApply.setReserve3("");
			} else if (pApply.getReserve2() == null || "".equals(pApply.getReserve2())) {
				pickApply.setReserve2("");
				pickApply.setReserve3("");
			} else if (pApply.getOrderSN() == null || "".equals(pApply.getOrderSN())) {
				pickApply.setReserve2(pApply.getReserve2());
				pickApply.setReserve3(pApply.getReserve3());
			} else {
				pickApply.setReserve2(pApply.getOrderSN());
				pickApply.setReserve3(pApply.getOrderNum());
			}
			return pickApply;
		} else {
			//排产单不存在
			return null;
		}
	}
	
	/**
	 * 生成随机数
	 * @param digCount 随机数位数
	 * @return
	 */
	public static String getRandomNumber(int digCount) {
		Random rnd = new Random();
	    StringBuilder sb = new StringBuilder(digCount);
	    for(int i=0; i < digCount; i++)
	        sb.append((char)('0' + rnd.nextInt(10)));
	    return sb.toString();
	}

	/**
	 * 撤销审批
	 */
	@Transactional(rollbackFor={Exception.class})
	public Integer cancelPickApply(ApprovalRecord approvalRecord, HttpSession session) {
		// TODO Auto-generated method stub
		int isSuccess = 0;
		try {
			User user = (User) session.getAttribute("currentUser");
			PickApply pickApply = pickApplyMapper.findPickApplyByID(approvalRecord.getPickID());
			pickApply.setReserve1("2");
			isSuccess = pickApplyMapper.updatePickApply(pickApply);
			List<ApprovalRecord> approvalRecords = approvalRecordMapper.listAllApprovalRecord(approvalRecord.getPickID());
			for (int i = 0; i < approvalRecords.size(); i++) {
				ApprovalRecord aRecord = approvalRecords.get(i);
				if (aRecord.getStatus() == 1) {
					isSuccess = approvalRecordMapper.deleteApprovalRecord(aRecord.getArID());
				}
			}
			approvalRecord.setApprovalType("撤销领料申请单审批");
			approvalRecord.setSubmitDate(new Date());
			approvalRecord.setSubmitterID(user.getUid());
			approvalRecord.setStatus(2);
			isSuccess = approvalRecordMapper.insertApprovalRecord(approvalRecord);
		} catch (Exception e) {
			e.printStackTrace();     
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			isSuccess = 0;
		}
		return isSuccess;
	}

	@Override
	public PickApply findPickApplyByID(Long pickID) {
		// TODO Auto-generated method stub
		return pickApplyMapper.findPickApplyByID(pickID);
	}

	@Transactional(rollbackFor={Exception.class})
	public Integer approvalPickApply2(ApprovalRecord approvalRecord, HttpSession session) {
		// TODO Auto-generated method stub
		int isSuccess = 0;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			User user = (User) session.getAttribute("currentUser");
			PickApply pickApply = pickApplyMapper.findPickApplyByID(approvalRecord.getPickID());
//			pickApply.setApplicant(user.getUid());
			if (approvalRecord.getApproverID() == null || "".equals(approvalRecord.getApproverID())) {
				pickApply.setApplicant(user.getUid());
			} else {
				pickApply.setApplicant(approvalRecord.getApproverID());
			}
			pickApply.setApprovalDate(new Date());
			pickApply.setReserve1(approvalRecord.getReserve1());
			isSuccess = pickApplyMapper.approvalPickApply(pickApply);
			List<ApprovalRecord> approvalRecordList = approvalRecordMapper.listAllApprovalRecord(approvalRecord.getPickID());
			for (int i = 0; i < approvalRecordList.size(); i++) {
				if (1 == approvalRecordList.get(i).getStatus()) {
					isSuccess = approvalRecordMapper.deleteApprovalRecord(approvalRecordList.get(i).getArID());
				}
			}
			approvalRecord.setApprovalType("处理领料申请单审批");
			approvalRecord.setSubmitDate(new Date());
			approvalRecord.setSubmitterID(pickApply.getPickPerson());
//			approvalRecord.setApproverID(user.getUid());
			if (approvalRecord.getApproverID() == null || "".equals(approvalRecord.getApproverID())) {
				approvalRecord.setApproverID(user.getUid());
			} else {
				approvalRecord.setApproverID(approvalRecord.getApproverID());
			}
			approvalRecord.setStatus(Integer.parseInt(approvalRecord.getReserve1()));
			approvalRecord.setReserve5("0");
			isSuccess = approvalRecordMapper.insertApprovalRecord(approvalRecord);
			if ("3".equals(approvalRecord.getReserve1())) {
				//审批通过去缓存区判断拉料
				PickApplyDetail pickApplyDetail = new PickApplyDetail();
				pickApplyDetail.setPickID(approvalRecord.getPickID());
				List<PickApplyDetail> pickApplyDetailList = pickApplyDetailMapper.listAllPickApplyDetail(pickApplyDetail);
				for (int i = 0; i < pickApplyDetailList.size(); i++) {
					Part part = partMapper.findPartByPanum(pickApplyDetailList.get(i).getStockNum());
					CacheArea cacheArea = new CacheArea();
					cacheArea.setPaID(part.getPaid());
					cacheArea.setBatch(pickApplyDetailList.get(i).getReserve3());
					CacheArea cacheArea2 = cacheAreaMapper.findCacheArea(cacheArea);
					if (null == cacheArea2) {
						cacheArea.setQuantity(pickApplyDetailList.get(i).getQuantity());
						isSuccess = cacheAreaMapper.insertCacheArea(cacheArea);
					} else {
						String cQuantity = StringUtil.calcFloatValue(cacheArea2.getQuantity(), pickApplyDetailList.get(i).getQuantity(), "add");
						cacheArea2.setQuantity(cQuantity);
						isSuccess = cacheAreaMapper.updateCacheArea(cacheArea2);
					}
					CacheAreaIn cacheAreaIn = new CacheAreaIn();
					cacheAreaIn.setPaID(part.getPaid());
					cacheAreaIn.setInQuantity(pickApplyDetailList.get(i).getQuantity());
					cacheAreaIn.setInDate(new Date());
					cacheAreaIn.setReserve1(pickApply.getReserve4());
					if ("2".equals(pickApply.getReserve4())) {
						cacheAreaIn.setReserve2(sdf.format(pickApply.getDemandDate()));
					} else {
						cacheAreaIn.setReserve2("");
					}
					cacheAreaIn.setBatch(pickApplyDetailList.get(i).getReserve3());
					isSuccess = cacheAreaInMapper.insertCacheAreaIn(cacheAreaIn);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();     
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			isSuccess = 0;
		}
		return isSuccess;
	}

	@Override
	public List<MaterialComparison> listAllMaterialComparison(String time) {
		// TODO Auto-generated method stub
		Shedudetail shedudetail = pickApplyMapper.findShedudetailByDate(time);
		if (null != shedudetail) {
			String b1 = shedudetail.getB1();//0960T 个数
			String c1 = shedudetail.getC1();//0980T	个数
			String d1 = shedudetail.getD1();//1080C	个数
			String e1 = shedudetail.getE1();//1060B 个数
			if(b1==null){
				b1="";
			}
			if(c1==null){
				c1="";
			}
			if(d1==null){
				d1="";
			}
			if(e1==null){
				e1="";
			}
			List<Product> pList = productMapper.listAllProduct(new Product());
			List<Bom> b_boms = new ArrayList<>();
			List<Bom> c_boms = new ArrayList<>();
			List<Bom> d_boms = new ArrayList<>();
			List<Bom> e_boms = new ArrayList<>();
			for (int i = 0; i < pList.size(); i++) {
				Product p = pList.get(i);
				if (p.getPnum().equals("PSH2-0960-T-01")) {
					b_boms = bomMapper.listAllBom(p.getPid());
				} else if (p.getPnum().equals("PSH2-0980-T-02")) {
					c_boms = bomMapper.listAllBom(p.getPid());
				} else if (p.getPnum().equals("PSH1-1080-C-04")) {
					d_boms = bomMapper.listAllBom(p.getPid());
				} else {
					e_boms = bomMapper.listAllBom(p.getPid());
				}
			}
			List<Bom> all_boms = new ArrayList<>();
			if (!"".equals(b1)) {
				for (int i = 0; i < b_boms.size(); i++) {
					Bom bom = new Bom();
					bom.setPaid(b_boms.get(i).getPaid());
					bom.setNumber(StringUtil.calcFloatValue(b_boms.get(i).getNumber(), b1, "multiply"));
					all_boms.add(bom);
				}
			}
			if (!"".equals(c1)) {
				for (int i = 0; i < c_boms.size(); i++) {
					Bom bom = new Bom();
					bom.setPaid(c_boms.get(i).getPaid());
					bom.setNumber(StringUtil.calcFloatValue(c_boms.get(i).getNumber(), c1, "multiply"));
					all_boms.add(bom);
				}
			}
			if (!"".equals(d1)) {
				for (int i = 0; i < d_boms.size(); i++) {
					Bom bom = new Bom();
					bom.setPaid(d_boms.get(i).getPaid());
					bom.setNumber(StringUtil.calcFloatValue(d_boms.get(i).getNumber(), d1, "multiply"));
					all_boms.add(bom);
				}
			}
			if (!"".equals(e1)) {
				for (int i = 0; i < e_boms.size(); i++) {
					Bom bom = new Bom();
					bom.setPaid(e_boms.get(i).getPaid());
					bom.setNumber(StringUtil.calcFloatValue(d_boms.get(i).getNumber(), e1, "multiply"));
					all_boms.add(bom);
				}
			}
			List<Bom> all_boms2 = new ArrayList<>();
			for (int i = 0; i < all_boms.size(); i++) {
				Bom bom = all_boms.get(i);
				String number = "0";
				for (int j = 0; j < all_boms.size(); j++) {
					if (bom.getPaid().equals(all_boms.get(j).getPaid())) {
						number = StringUtil.calcFloatValue(number, all_boms.get(j).getNumber(), "add");
					}
				}
				Bom b = new Bom();
				b.setPaid(bom.getPaid());
				b.setNumber(number);
				all_boms2.add(b);
			}
			for (int i = 0; i < all_boms2.size() -1; i++) {
				for (int j = all_boms2.size() - 1; j > i; j--) {
					if (all_boms2.get(i).getPaid().equals(all_boms2.get(j).getPaid())) {
						all_boms2.remove(j);
					}
				}
			}
			List<LineSideLibraryOut> lOuts = pickApplyMapper.listActualQuantity(time);
			List<MaterialComparison> mList = new ArrayList<>();
			for (int i = 0; i < all_boms2.size(); i++) {
				Bom bom = all_boms2.get(i);
				Part part = partMapper.findPartByPaid(bom.getPaid());
				MaterialComparison m = new MaterialComparison();
				m.setPanum(part.getPanum());
				m.setPaname(part.getPaname());
				m.setPamodel(part.getPamodel());
				m.setPaunit(part.getParemark1());
				m.setPackNorm(part.getParemark2());
				m.setTheoryQuantity(bom.getNumber());
				int x = 0;
				for (int j = 0; j < lOuts.size(); j++) {
					LineSideLibraryOut lOut = lOuts.get(j);
					if (bom.getPaid() == lOut.getPaID()) { 
						x = 1;
						m.setActualQuantity(round(lOut.getActualQuantity()));
						String deviation = round(StringUtil.calcFloatValue(lOut.getActualQuantity(), bom.getNumber(), "subtract"));
						
						if ((int)Double.parseDouble(deviation) == 0) {
							m.setDeviationRate("0");
						} else {
							NumberFormat nt = NumberFormat.getPercentInstance();
							nt.setMinimumFractionDigits(2);
							m.setDeviationRate(StringUtil.calcFloatValue(deviation, bom.getNumber(), "divide"));
						}
					}
				}
				if(x==0){
					m.setDeviationRate("100%");
				}
				mList.add(m);
			}
			return mList;
		} else {
			return null;
		}
	}

	@Override
	public Shedudetail findShedudetailByDate(String remark1) {
		return pickApplyMapper.findShedudetailByDate(remark1);
	}
	public String round(String d){
		BigDecimal bg = new BigDecimal(d).setScale(4, BigDecimal.ROUND_CEILING);
		String bgStr = bg.toString();
		Double bgDou = Double.parseDouble(bgStr);
		return bgDou.toString();
	}
}
